package com.um.swing.common.inc;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.um.swing.bean.ConfigBean;
import com.um.swing.bean.ImageItem;
import com.um.swing.common.exception.BizException;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Map;

/**
 * 名称：工程配置文件类,单例模式
 * 创建人：袁泉
 * 创建时间：2022年04月26日20:10:37
 */
public class Config {
    private static Config __instance = null;
    private static final String configDirName = ".config";//配置目录名称
    private static final String configFileName = "base.conf";//配置文件名称

    private ObjectMapper mMapper = new ObjectMapper();

    private String mWorkSpaceName;//工作空间名称
    private String mWorkSpacePath;//工作空间路径
    private String mConfigFilePath;//配置文件目录
    private ConfigBean mCfgObject;//配置信息类
    private Charset mCharset = Charset.forName("utf-8");//配置文件编码

    public ConfigBean getCfgObject() {
        return mCfgObject;
    }

    private Config() {
    }

    public static Config getInstance() {
        if (__instance == null) {
            try {
                __instance = new Config();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return __instance;
    }

    /**
     * 初始化工作空间
     *
     * @param wName
     * @param wPath
     * @return
     */
    public ConfigBean initConfig(String wName, String wPath) {
        if (StrUtil.hasBlank(wName, wPath)) {
            throw new BizException("工作空间名称或路径有误");
        }
        //判断是否有配置目录，如 果有，则读取，如果么有则创建配置
        this.mWorkSpaceName = wName;
        this.mWorkSpacePath = wPath;
        File wsFile = new File(wPath);
        if (!wsFile.exists()) {
            throw new BizException("工作空间不存在");
        }
        String configPath = wPath;
        if (StrUtil.endWith(wPath, "/")) {
            configPath = configPath.substring(0, configPath.length() - 1);
        }
        configPath += File.separator + configDirName;
        File cfgDir = new File(configPath);
        if (!cfgDir.exists()) {
            cfgDir.mkdir();
        }
        //判断是否有配置文件
        configPath += File.separator + configFileName;
        this.mConfigFilePath = configPath;
        File cfgFile = new File(configPath);
        if (!cfgFile.exists()) {
            mCfgObject = new ConfigBean();
            save();
        } else {
            String cfgStr = FileUtil.readString(cfgFile, mCharset);
            if (StrUtil.isNotBlank(cfgStr)) {
                try {
                    mCfgObject = mMapper.readValue(cfgStr, ConfigBean.class);
                } catch (Exception e) {
                    mCfgObject = new ConfigBean();
                    throw new BizException("读取配置文件异常");
                }
            }
        }
        return ObjectUtil.clone(mCfgObject);
    }

    /**
     * 更新配置：当前正在操作的图片下标
     *
     * @param curIndex
     */
    public void updateCurIndex(int curIndex) {
        this.mCfgObject.setCurProcIndex(curIndex);
        save();
    }

    /**
     * 更新图片Item
     *
     * @param item
     * @return
     */
    public ImageItem updateImageItem(ImageItem item, boolean isSave) {
        if (item == null) return item;
        ImageItem cItem = ObjectUtil.clone(item);
        if (item.getPreviewImage() != null) {
            cItem.setPreviewImage(null);
        }
        Map<String, ImageItem> imgMap = this.mCfgObject.getImageData();
        imgMap.put(cItem.getName(), cItem);
        try {
            if (isSave) save();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cItem;
    }

    /**
     * 保存配置
     */
    public void save() {
        File cfgFile = new File(this.mConfigFilePath);
        if (!cfgFile.exists()) {
            try {
                cfgFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                throw new BizException("创建配置文件失败");
            }
        }
        try {
            String json = mMapper.writerWithDefaultPrettyPrinter().writeValueAsString(mCfgObject);
            FileUtil.writeString(json, cfgFile, mCharset);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }
}
